package com.summer.shopping.chat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.summer.shopping.chat.handler.WSInfoTypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
@Component
public class ChatCore extends TextWebSocketHandler {

    @Autowired
    private UserChatPool userChatPool;
    @Autowired
    List<WSInfoTypeHandler> handlers;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        userChatPool.addUser(userId(session),session);
    }


    /**
     * @see WSInfo
     *  {
     *      type: "xxx",         这里是消息类型，比如："info"
     *      content: "xxx",         这里是消息内容
     *      to: "xxx",           这里是userId
     *  }
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        WSInfo info = objectMapper.readValue(payload, WSInfo.class);
        for (WSInfoTypeHandler handler : handlers) {
            if (handler.isSupport(info.getType())){
                handler.handleInfo(info.toStandard(session,userChatPool));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        userChatPool.removeUser(session);
    }


    private Long userId(WebSocketSession session) {
        return (Long) session.getAttributes().get("userId");
    }
}
